<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jquery ajax请求</title>
</head>

<body>
  <input type="text" id="username" name="username" placeholder="username" />
  <span id="usernameHint"></span>

  <script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.6.0/jquery.min.js" type="application/javascript"></script>

  <script>
    $('#username').blur(function () {
      //发送ajax请求
      /*  $.get('http://localhost:8888/AjaxTeach/user/check?username=' + $('#username').val(), function (result) {
         if (result == '1') {
           usernameHint.innerHTML = '该用户已被注册!'
         } else {
           usernameHint.innerHTML = ''
         }
       }) */


      /* $.post('http://localhost:8888/AjaxTeach/user/check', {
        'username': $('#username').val()
      }, function (result) {
        if (result == '1') {
          usernameHint.innerHTML = '该用户已被注册!'
        } else {
          usernameHint.innerHTML = ''
        }
      }) */

      //更通用,更灵活
      $.ajax({
        //同步还是异步,默认true表示异步
        async: true,
        //请求类型,jq1.9之后提供了新的属性method,但是type更为兼容,适合所有版本
        type: 'post',
        //请求地址
        url: 'http://localhost:8888/AjaxTeach/user/check',
        //请求数据
        data: {
          username: $('#username').val()
        },
        //响应结果
        //成功
        success(result, status, xhr) {
          if (result == '1') {
            usernameHint.innerHTML = '该用户已被注册!'
          } else {
            usernameHint.innerHTML = ''
          }
        },
        //失败
        error(xhr, status, error) {
          console.log('请求失败...');
        }
      })
    })
  </script>
</body>

</html>